package com.example.myapplication;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class ListenerActivity extends AppCompatActivity  implements View.OnClickListener,View.OnKeyListener{
        ImageButton[] buttons = new ImageButton[2];
        private TextView tv_choose,tv_info;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listener_layout);
        buttons[0] =(ImageButton) findViewById(R.id.ib_img1);
        buttons[1] =(ImageButton) findViewById(R.id.ib_img2);
        tv_choose = (TextView) findViewById(R.id.tv_choose);
        tv_info = (TextView) findViewById(R.id.tv_info);
        tv_info.setText("请使用键盘中的A，B键控制下方两个按钮图片");
        for (ImageButton button :buttons){
            button.setOnClickListener(this);
            button.setOnKeyListener(this);
        }
    }
    public  void onClick(View v){
        switch (v.getId()){
            case R.id.ib_img1:
                tv_choose.setText("你点击了按钮A");
                break;
            case R.id.ib_img2:
                tv_info.setText("你点击了按钮B");
                break;
        }
    }
    public boolean onKey(View v, int keyCode, KeyEvent keyEvent){
        switch (keyCode){
            case KeyEvent.KEYCODE_A:
                buttons[0].performClick();
                buttons[0].requestFocus();
                break;
            case KeyEvent.KEYCODE_B:
                buttons[1].performClick();
                buttons[1].requestFocus();
                break;
        }
        return false;
    }
}
